<?php
namespace App\Utility;
use EasySwoole\HttpClient\HttpClient;

class ZtSms
{

    private static $instance = null;
    private $username;
    private $password;
    private $sign;
    private $balance = "https://api.mix2.zthysms.com/v2/balance";
    private $sendSms = "https://api.mix2.zthysms.com/v2/sendSms";

    private function __construct($username,$password,$sign)
    {
        $this->username = $username;
        $this->password = $password;
        $this->sign   = $sign;
    }

    public static function getInstance($username = "",$password="",$sign="【测试】")
    {
        if(self::$instance === null){
            self::$instance = new self($username,$password,$sign);
        }
        return self::$instance;
    }

    public function balance(){

        $http = new HttpClient($this->balance);
        $timestamp = time();
        $params = [
            'username' => $this->username,
            'password' => md5(md5($this->password).$timestamp),
            'tKey'    => $timestamp
        ];

        $res = $http->postJson(json_encode($params));
        $data = json_decode($res->getBody(),true);

        if($data['code'] != 200){

            return false;
        }

        return $data['sumSms'];

    }

    /**
     * 发送短信
     * @param $mobile
     * @param $code
     * @return bool
     * @throws \EasySwoole\HttpClient\Exception\InvalidUrl
     */
    public function sendSms($mobile,$code){

        $http = new HttpClient($this->sendSms);
        $timestamp = time();

        $params = [
            'username' => $this->username,
            'password' => md5(md5($this->password).$timestamp),
            'tKey'    => $timestamp,
            'mobile'   =>  $mobile,
            'content'  =>  "{$this->sign}尊敬的用户您好,您的手机验证码为:{$code},有效期15分钟,请妥善保管请勿泄露他人！"
        ];

        $res = $http->postJson(json_encode($params));

        $data = json_decode($res->getBody(),true);

        if($data['code'] != 200){

            return false;
        }

        return true;

    }
}

?>